package com.enation.app.javashop.core.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.member.plugin.wechat.WechatConnectLoginPlugin;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatSignaturer;
import com.enation.app.javashop.core.system.enums.WechatMiniproTemplateTypeEnum;
import com.enation.app.javashop.core.system.model.dos.WechatMsgTemplate;
import com.enation.app.javashop.core.system.model.dto.MiniproSendMsgDTO;
import com.enation.app.javashop.core.system.service.WechatMiniproTemplateManager;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.util.EnvironmentUtils;
import com.enation.app.javashop.framework.util.HttpUtils;
import com.enation.app.javashop.framework.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信小程序模板发送类
 */
@Service
public class WechatMiniproTemplateManagerImpl implements WechatMiniproTemplateManager {

    @Autowired
    @Qualifier("systemDaoSupport")
    private DaoSupport daoSupport;
    @Autowired
    private WechatSignaturer wechatSignaturer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    public WechatConnectLoginPlugin wechatConnectLoginPlugin;

    protected final Log logger = LogFactory.getLog(this.getClass());


    /**
     * 发送模板数据
     */
    @Override
    public void send(MiniproSendMsgDTO miniproSendMsgDTO) {
        if(StringUtil.isEmpty(miniproSendMsgDTO.getOpenId())){
            return;
        }

        WechatMiniproTemplateTypeEnum templateTypeEnum = miniproSendMsgDTO.getTemplateTypeEnum();

        //使用枚举查看模板
        String sql = "select * from es_wechat_msg_template where tmp_type = ?";
        WechatMsgTemplate template = this.daoSupport.queryForObject(sql, WechatMsgTemplate.class, templateTypeEnum.value());
        //判断模板是否开启，开启则发消息
        if (template == null || template.getIsOpen().equals(0)) {
            return;
        }

        //获取token
        String accessToken = wechatConnectLoginPlugin.getWXAccessToken();
        //发送url
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

        // 小程序模板参数
        Map<String, Object> map = new HashMap<>();
        map.put("touser", miniproSendMsgDTO.getOpenId());
        map.put("template_id", template.getTemplateId());
        map.put("page", templateTypeEnum.getPage() + miniproSendMsgDTO.getPageParams());
        map.put("data", miniproSendMsgDTO.getDataMap());

        if(EnvironmentUtils.isProd()){
            map.put("miniprogramState","formal");
        }else{
            map.put("miniprogramState","trial");
        }

        String uuid = UUID.randomUUID().toString().replace("-", "");
        logger.debug("小程序发送消息请求报文" + uuid + ":" + JSON.toJSON(map).toString());
        String content = HttpUtils.doPostWithJson(url, map);
        logger.debug("小程序发送消息响应报文" + uuid + ":" + JSON.toJSON(content).toString());
        JSONObject json = JSONObject.fromObject(content);
        String errMsg = json.get("errmsg").toString();
        if (!"ok".equals(errMsg) && logger.isDebugEnabled()) {
            logger.debug("小程序发送消息错误，返回内容：" + content);
        }
    }

}
